package com.ruoyi.common.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/*
@description:
@ClassName AESUtils
@author chen
@create 2025-01-09 17:02
@Version 1.0
*/
public class AESUtils
{
    private static String key = "derwqewrqwerwTVo";
    private static String iv = "dre5xsvbzs6nor39";

    public static void main(String[] args)
    {
        String strJson = "******";
        String returnEncrypt = encrypt(strJson);
        System.out.println(returnEncrypt);

        String returnDesEncrypt = desEncrypt(returnEncrypt);
        System.out.println(returnDesEncrypt);
    }

    /*
     * @==============History===============<br/>;
     * @Description //   AES加密
     * @Date 2025/1/9
     * @Author < a href="chencheng@prmt.net">chen</ a>;
     */
    public static String encrypt(String data)
    {
        Cipher cipher;
        try
        {
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if(plaintextLength % blockSize !=0)
            {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes,0, plaintext,0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(),"AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new Base64().encodeToString(encrypted);
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }



    /*
     * @==============History===============<br/>;
     * @Description //   AES解密
     * @Date 2025/1/9
     * @Author < a href="chencheng@prmt.net">chen</ a>;
     */
    public static String desEncrypt(String data)
    {
        Cipher cipher;
        try {
            byte[] encrypted1 = new Base64().decode(data);
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original).trim();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

}
